const express = require('express');
const router = express.Router();
const User = require('../models/user');
const { success, failure } = require('../utils/responses');
const { BadRequestError, NotFoundError } = require('../utils/errors');
const bcrypt = require('bcryptjs');

// 查询当前登录用户详情
router.get('/me', async function (req, res) {
    try {
        const user = await getUser(req);
        success(res, '查询当前用户信息成功。', { user });
    } catch (error) {
        console.log('~~~~~~~~~~');
        failure(res, error);
    }
});

// 更新用户基本信息（如昵称、性别等）
router.put('/info', async function (req, res) {
    try {
      console.log(req.user._id);
        const body = {
            nickname: req.body.nickname,
            sex: req.body.sex,
            company: req.body.company,
            introduce: req.body.introduce,
            avatar: req.body.avatar
        };

        const user = await getUser(req);
        await User.updateOne({ _id: user._id }, body);
        Object.assign(user, body);
        const updatedUser = await getUser(req);
        success(res, '更新用户信息成功。', { user: updatedUser });
    } catch (error) {
        failure(res, error);
    }
});

// 更新用户账户信息（包含密码相关操作）
router.put('/account', async function (req, res) {
    try {
        const body = {
            current_password: req.body.current_password,
            password: req.body.password,
            passwordConfirmation: req.body.passwordConfirmation
        };
        console.log(body);

        if (!body.current_password) {
            throw new BadRequestError('请输入当前密码。');
        }

        if ((body.password.length < 6 || body.password.length > 45) && body.password!== body.passwordConfirmation) {
            throw new BadRequestError('两次输入的密码不一致且密码长度必须是6 ~ 45之间。');
        }
    
        const user = await getUser(req, true);

        const isPasswordValid = await bcrypt.compare(body.current_password, user.password);
        if (!isPasswordValid) {
            throw new BadRequestError('当前密码错误。');
        }

        // 如果密码验证通过，更新除密码外的其他信息（密码需要单独处理哈希）
        delete body.current_password;
        delete body.passwordConfirmation;
        console.log(body);
        body.password = await bcrypt.hash(body.password, 10);
        await User.updateOne({ _id: user._id }, { $set: body });
        // Object.assign(user, body);

        if (body.password) {
            user.password = await bcrypt.hash(body.password, 10);
        }

        // await user.save();
        user.password = undefined;
        success(res, '更新用户信息成功。', { user });
    } catch (error) {
      console.log(error);
        failure(res, error);
    }
});

// 公共方法：查询当前用户
async function getUser(req, showPassword = false) {
    const id = req.user._id;
    let projection = {};
    if (!showPassword) {
        projection = { password: 0 };
    }

    const user = await User.findById(id, projection);
    if (!user) {
        throw new NotFoundError(`ID: ${id}的用户未找到。`);
    }

    return user;
}

module.exports = router;